package com.erp.util;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.erp.BuildConfig;
import com.erp.Interface.OnUserDataInterface;
import com.erp.R;
import com.erp.bean.AddJiaFangBean;
import com.erp.bean.CaiLiaoZhiLiangBean;
import com.erp.bean.ClientDataBean;
import com.erp.bean.CrmSouSuoBean;
import com.erp.bean.OrderSousuoBean;
import com.erp.bean.ProdyctionClientBean;
import com.erp.bean.TouSuBean;
import com.erp.bean.TouSuSouSuoBean;
import com.erp.bean.Twostringbean;
import com.erp.bean.ZhiLiangBean;
import com.erp.contacts.Contacts;
import com.erp.mclass.QuanXian;
import com.erp.mclass.Tls12SocketFactory;
import com.erp.module.faHuoDanJu.faHuo1.FragmentFahuo;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import static com.erp.contacts.Contacts.BOUNDARY;
import static com.erp.util.Myutil.dateToStamp;

/**
 * Created by Administrator on 2016/11/7/007.
 * 作者：刘洋
 * 所有网络访问的工具类
 */
public class Httputil {
    public static int HTTP_NO = 1;
    /*** 网络访问获取用户数据*/
    public static void setuserdatahttp(Context context, int page, int pagesize, final String[] fields, CrmSouSuoBean souSuoBean, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.USERDATA);
        getparams(context, params);
        params.addBodyParameter("page", String.valueOf(page));
        params.addBodyParameter("pagesize", String.valueOf(pagesize));
        if (fields != null) {
            for (int i = 0; i < fields.length; i++) {
                params.addBodyParameter("fields[" + i + "]", fields[i]);
            }
        }
        params.addBodyParameter("searchParams[all]", souSuoBean.all);
        if(!souSuoBean.xiaoshouyuan_uid.equals("")) {
            params.addBodyParameter("searchParams[xiaoshouyuan_uid][1]", souSuoBean.xiaoshouyuan_uid);
        }
        if(!souSuoBean.shejishi_uid.equals("")) {
            params.addBodyParameter("searchParams[designer_uid][1]", souSuoBean.shejishi_uid);
        }
        params.addBodyParameter("searchParams[customer_name]", souSuoBean.kehuming);
        params.addBodyParameter("searchParams[customer_tel]", souSuoBean.shoujihao);
        params.addBodyParameter("searchParams[onum]", souSuoBean.shengchan);
        params.addBodyParameter("searchParams[contract_num]", souSuoBean.hetong);
        params.addBodyParameter("searchParams[status]", souSuoBean.status);
        if(!souSuoBean.time_category.equals("")){
            params.addBodyParameter("searchParams[time_filter][time_category]", souSuoBean.time_category);
            params.addBodyParameter("searchParams[time_filter][start_time]", souSuoBean.start_time);
            params.addBodyParameter("searchParams[time_filter][end_time]", souSuoBean.end_time);
        }
        Log.d("TAAG","cookie="+Sputil.sp("erp").getString("cookie", ""));
        Log.d("TAAG","TOKEN="+Sputil.sp("erp").getString("token", ""));
        x.http().get(params, Call(context, onUserDataInterface));
    }

    /**
     * 登陆
     *
     * @param name     账号
     * @param password 密码
     */
    public static void setLogin(Context context, String name, String password, String child_name, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.LOGIN);
        Log.e("TAAAG", params.toString());
        if(params==null) {
            Log.e("TAAAG", "bbbbbbbbbbbb");
        }
        addssl(params, context);
        params.addBodyParameter("username", name, BOUNDARY);
        params.addBodyParameter("password", password, BOUNDARY);
        if (child_name != "") {
            params.addBodyParameter("child_name", child_name, BOUNDARY);
        }
        params.addHeader("ACCEPT", "application/json");
        params.setConnectTimeout(6000);
        x.http().post(params, Call(context,onUserDataInterface));
    }

    /**退出登录*/
    public static void setLogout(Context context, final OnUserDataInterface onuserdatainterface) {
        RequestParams params = new RequestParams(Contacts.LOGOUT);
        getparams(context, params);
        addtoken(params);
        params.addHeader("Content-Type", "multipart/form-data");
        x.http().post(params, Call(context,onuserdatainterface));
    }

    /**卡诺亚DingDIng验证*/
    public static void setDingDIng(Context context,String code ,final OnUserDataInterface onuserdatainterface) {
        RequestParams params = new RequestParams(Contacts.DINGDING);
        addssl(params,context);
        params.addBodyParameter("authcode",code, BOUNDARY);
        params.addBodyParameter("","", BOUNDARY);
        x.http().post(params, Call(context,onuserdatainterface));
    }

    /**工程公司DingDIng验证*/
    public static void setGongChengDingDIng(Context context,String code ,final OnUserDataInterface onuserdatainterface) {
        RequestParams params = new RequestParams(Contacts.GONGCHENG_DINGDING);
        addssl(params,context);
        params.addBodyParameter("authcode",code, BOUNDARY);
        params.addBodyParameter("","", BOUNDARY);
        x.http().post(params, Call(context,onuserdatainterface));
    }
//    f566252e66340e676df1be5dac0d37fa
//73af5e710a2bcfe507744186a18aeac8

    /**获取token*/
    public static void getToken(Context context, final OnUserDataInterface onuserdatainterface) {
        RequestParams params = new RequestParams(Contacts.TOKEN);
        getparams(context, params);
        params.addBodyParameter("page", "1111",BOUNDARY);
        params.addBodyParameter("pagesize", "1111",BOUNDARY);
        params.addHeader("Content-Type", "multipart/form-data");
        x.http().post(params, Call(context,onuserdatainterface));
    }

    /**
     * 获取子帐号方法
     *
     * @param page                获取的页数
     * @param pagesize            每页获取的数据条目
     * @param onUserDataInterface
     */
    public static void getHttpBypass(Context context, int page, int pagesize, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.BYPASS);
        getparams(context, params);
        params.addBodyParameter("page", String.valueOf(page));
        params.addBodyParameter("pagesize", String.valueOf(pagesize));
        x.http().get(params, Call(context,onUserDataInterface));
    }
    /**
     * 获取门店经理
     *
     * @param onUserDataInterface
     */
    public static void getmanager(Context context, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.MANAGER);
        getparams(context, params);
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /**
     * 获取子账号详细数据
     *
     * @param uid                 选中的子账号id
     * @param onUserDataInterface
     */
    public static void getHttpDetailBypass(Context context, String uid, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.BYPASS + "/" + uid);
        getparams(context, params);
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /**
     * 客户详细数据获取方法
     *
     * @param crm_uid             选中的客户id
     * @param onUserDataInterface
     */
    public static void getHttpClient(Context context, String crm_uid, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.USERDATA + "/" + crm_uid);
        getparams(context, params);
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /**
     * 获取生产单列表
     *
     * @param page                获取的页数
     * @param pagesize            每页获取的数据条目
     * @param onUserDataInterface
     */
    public static void getHttpOrder(Context context, String page, String pagesize, OrderSousuoBean bean, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.PRODUCTION);
        getparams(context, params);
        params.addBodyParameter("page", page);
        params.addBodyParameter("pagesize", pagesize);
        params.addBodyParameter("searchParams[all]", bean.all);
        params.addBodyParameter("searchParams[onum]", bean.onum);
        params.addBodyParameter("searchParams[o_contract_num_like]", bean.o_contract_num_like);
        params.addBodyParameter("searchParams[o_customer_like]", bean.o_customer_like);
        params.addBodyParameter("searchParams[province]", bean.province);
        params.addBodyParameter("searchParams[area]", bean.area);
        params.addBodyParameter("searchParams[o_type]", bean.o_type);
        params.addBodyParameter("searchParams[is_canceled]", bean.is_canceled);
        params.addBodyParameter("searchParams[field_empty]", bean.field_empty);
        params.addBodyParameter("searchParams[field_not_empty]", bean.field_not_empty);
        params.addBodyParameter("searchParams[shop_name]", bean.shop_name);
        if(bean.special_service_cat.size()>0){
            for(int i=0;i<bean.special_service_cat.size();i++) {
                params.addBodyParameter("searchParams[special_service_cat]["+i+"]", bean.special_service_cat.get(i));
            }
        }
        if(!bean.time_category.equals("")){
            params.addBodyParameter("searchParams[time_filter][time_category]", bean.time_category);
            params.addBodyParameter("searchParams[time_filter][start_time]", bean.start_time);
            params.addBodyParameter("searchParams[time_filter][end_time]", bean.end_time);
        }
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /** 获取生产单详情*/
    public static void getHttpProdyctionClient(Context context, String id, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.PRODUCTION + "/" + id);
        getparams(context, params);
        setProsess(params);
        Log.d("jsondata","params="+params.toString());
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /** 客户状态归类汇总*/
    public static void getHttpState(Context context, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.STATE);
        getparams(context, params);
        params.addHeader("Content-Type", "multipart/form-data");
        addtoken(params);
        x.http().post(params, Call(context,onUserDataInterface));
    }


    /** 获取最新版本号数据*/
    public static void getUpdateInfo(Context context,final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.UPDATEINFO);
        x.http().get(params, Call(context,onUserDataInterface));
    }

    /** 下载apk*/
    public static void showUpdateInfo(Context context, String url, final String path, final ProgressBar pb, final TextView tv, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(url);
        params.setSaveFilePath(path);
        x.http().get(params, Callfile(context,onUserDataInterface, pb, tv));
    }


    /** 下载文件*/
    public static void showdownload(Context context, String url, final String path, final ProgressBar pb, final TextView tv, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(url);
        getparams(context, params);
        addtoken(params);
        params.setSaveFilePath(path);
        Log.d("showdownload",params.toString());
        x.http().get(params, Callfile(context,onUserDataInterface, pb, tv));
    }

    /** 上传图片*/
    public static void uplodingphoto(Context context, String id, String isname, JSONObject o, List<String> lists, String bt, String name, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.USERDATA + "/" + id);
        getparams(context, params);
        addtoken(params);
        JSONObject joo = null;
        try {
            JSONArray j = new JSONArray();
            JSONObject jo = new JSONObject();
            if(bt!=null&&name!=null) {
                jo.put("filecontents", bt);
                jo.put("filename", name);
                j.put(jo);
            }
            for(int i=0;i<lists.size();i++){
                JSONObject jj=new JSONObject();
                jj.put("fid",lists.get(i));
                j.put(jj);
            }

            if(isname == "measuring_scale"){
                o.getJSONObject(isname).put("msa_fids",j);
            }else if(isname == "ass"){
                o.getJSONObject(isname).put("ass_attachment",j);
            }else{
                o.getJSONObject(isname).put("attachment",j);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        params.setBodyContent(o.toString());
        x.http().request(HttpMethod.PUT, params, Call(context,onUserDataInterface));
    };

//    /** 上传图片*/
//    public static void uplodingphoto(Context context, String id, String isname, JSONObject os, List<String> lists, String bt, String name, final OnUserDataInterface onUserDataInterface) {
//        RequestParams params = new RequestParams(Contacts.USERDATA + "/" + id);
//        getparams(context, params);
//        addtoken(params);
//        JSONObject joo = null;
//        try {
//            joo = new JSONObject();
//            JSONObject o = new JSONObject();
//            JSONArray j = new JSONArray();
//            JSONObject jo = new JSONObject();
//            if(bt!=null&&name!=null) {
//                jo.put("filecontents", bt);
//                jo.put("filename", name);
//                j.put(jo);
//            }
//            for(int i=0;i<lists.size();i++){
//                JSONObject jj=new JSONObject();
//                jj.put("fid",lists.get(i));
//                j.put(jj);
//            }
//            o.put("attachment", j);
//            joo.put(isname, o);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.d("TAAAG","joo="+joo.toString());
//        params.setBodyContent(joo.toString());
//        x.http().request(HttpMethod.PUT, params, Call(context,onUserDataInterface));
//    };

    public static void cleanclient(Context context,String id,JSONObject jo,OnUserDataInterface onUserDataInterface){
        RequestParams params = new RequestParams(Contacts.USERDATA + "/" + id);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        params.setBodyContent(jo.toString());
        x.http().request(HttpMethod.PUT,params, Call(context,onUserDataInterface));
    }
    public static void addclient(Context context, ClientDataBean bean, OnUserDataInterface onUserDataInterface){
        RequestParams params = new RequestParams(Contacts.USERDATA );
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        Log.d("AddCrmActivity",bean.toString());
        params.addBodyParameter("values[name]",bean.name,BOUNDARY);
        params.addBodyParameter("values[tel]",bean.tel,BOUNDARY);
        params.addBodyParameter("values[sex]",bean.sex,BOUNDARY);
        params.addBodyParameter("values[wechat_number]",bean.wechat_number,BOUNDARY);
        params.addBodyParameter("values[age]",bean.age,BOUNDARY);
        params.addBodyParameter("values[occupation]",bean.occupation,BOUNDARY);
        params.addBodyParameter("values[kehulaiyuan]",bean.kehulaiyuan,BOUNDARY);
        params.addBodyParameter("values[demand]",bean.demand,BOUNDARY);
        params.addBodyParameter("values[remark]",bean.remark,BOUNDARY);
        params.addBodyParameter("values[customer_cat]",bean.customer_cat,BOUNDARY);
//        params.addBodyParameter("values[exclusive_shop]","测试专卖店",BOUNDARY);
//        bean.xiaoshouyuanid.size();
        for (int i=0;i<bean.xiaoshouyuanid.size()-1;i++){
            params.addBodyParameter("values[xiaoshouyuan]["+i+"]", bean.xiaoshouyuanid.get(i), BOUNDARY);
        }
        if(bean.store_manager_nameid != ""){
            params.addBodyParameter("values[store_manager]", bean.store_manager_nameid, BOUNDARY);
        }
        x.http().post(params, Call(context,onUserDataInterface));
    }
    /**上传设备id*/
    public static void setdeviceID(Context context, String deviceId, OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.DEVICEID);
        getparams(context, params);
        params.addBodyParameter("", "", BOUNDARY);
        params.addBodyParameter("deviceid", deviceId, BOUNDARY);
        addtoken(params);
        params.setConnectTimeout(6000);
        x.http().post(params, Call(context,onUserDataInterface));
    }

    /** 获取账户信息*/
    public static void gethttpuser(Context context, String uid, final OnUserDataInterface onUserDataInterface) {
        RequestParams params = new RequestParams(Contacts.USER + uid);
        getparams(context, params);
        params.setConnectTimeout(6000);
        x.http().get(params, Call(context,onUserDataInterface));
    }


    /** 扫描后获取专卖店的订单列表，以便于上传发货单据*/
    public static void getdingdan(Context context,String keyworld, OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.DINGDAN);
        getparams(context,params);
        params.addBodyParameter("", "", BOUNDARY);
        params.addBodyParameter("qr_code",keyworld, BOUNDARY);
        addtoken(params);
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /** 上传发货单据*/
    public static void setOploddanju(int type,Context context,List<String> listoid,String bt,String name,List<String> listcar,OnUserDataInterface onUserDataInterface){
        RequestParams params=null;
        if(type== FragmentFahuo.Companion.getDANJU()) {
            params = new RequestParams(Contacts.UPLODINGDANJU);
        }else if(type== FragmentFahuo.Companion.getQINGDAN()){
            params = new RequestParams(Contacts.UPLODINQINGDAN);
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        JSONObject joo = null;
        try {
            joo = new JSONObject();
            joo.put("filename",name);
            joo.put("filecontents",bt);
            JSONArray jsoid=new JSONArray();
            for(int i=0;i<listoid.size();i++){
                JSONObject joid=new JSONObject();
                joid.put("oid",listoid.get(i));
                joid.put("deliver_car_number",listcar.get(i));
                jsoid.put(joid);
            }
            joo.put("items",jsoid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        WriteStringToFile(joo.toString());
        params.setBodyContent(joo.toString());
        x.http().post(params,Call(context,onUserDataInterface));
    }

    public static void WriteStringToFile(String filePath) {
        try {
            File file = new File(Environment.getExternalStorageDirectory().toString() + "/erp/lll.txt");
            PrintStream ps = new PrintStream(new FileOutputStream(file));
            ps.println(filePath);// 往文件里写入字符串
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /** 获取单据列表*/
    public static void getdanju(int type,Context context,int page,int pagesize,String zhuanmaidian,String baohao,OnUserDataInterface onUserDataInterface){
        RequestParams params=null;
        if(type== FragmentFahuo.Companion.getDANJU()) {
            params = new RequestParams(Contacts.SHOWDANJU);
        }else if(type== FragmentFahuo.Companion.getQINGDAN()){
            params = new RequestParams(Contacts.SHOWQINGDAN);
        }
        getparams(context,params);
        setProsess(params);
        params.addBodyParameter("page",String.valueOf(page));
        params.addBodyParameter("pagesize",String.valueOf(pagesize));
        if(zhuanmaidian!=null){
            params.addBodyParameter("searchParams[shop_name]",zhuanmaidian);
        }
        if(baohao!=null){
            params.addBodyParameter("searchParams[onum]",baohao);
        }
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /** 删除单据*/
    public static void deletedanju(int type,Context context,String fid,OnUserDataInterface onUserDataInterface){
        RequestParams params=null;
        if(type== FragmentFahuo.Companion.getDANJU()) {
            params = new RequestParams(Contacts.SHOWDANJU);
        }else if(type== FragmentFahuo.Companion.getQINGDAN()){
            params = new RequestParams(Contacts.SHOWQINGDAN);
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        x.http().request(HttpMethod.DELETE,params,Call(context,onUserDataInterface));
    }

    /** 获取有问题的单据照片*/
    public static void getWtPhoto(int code,Context context,String uid, OnUserDataInterface onUserDataInterface) {
        RequestParams params = null;
        if(code==1){
            params=new RequestParams(Contacts.WT_PHOTO+uid);
        }else if(code==2){
            params=new RequestParams(Contacts.DD_PHOTO+uid);
        }else if(code==3){
            params=new RequestParams(Contacts.ANZHUANG_XPHOTO+uid);
        }else if(code==4){
            params=new RequestParams(Contacts.ZHUANMAIDIAN+uid);
        }
        getparams(context,params);
        setProsess(params);
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /**上传问题照片*/
    public static void getShangchuanPhoto(int code, Context context, List<String> photos, List<ProdyctionClientBean.guimingxi> listcid, String oid, OnUserDataInterface onUserDataInterface) {
        RequestParams params=null;
        if(code==1){
            params=new RequestParams(Contacts.SC_WT_PHOTO+oid);
        }else if(code==2){
            params=new RequestParams(Contacts.SC_DD_PHOTO+oid);
        }else if(code ==3 || code ==5){
            params=new RequestParams(Contacts.ANZHUANG_SHANGCHUAN+oid);
        }else if(code==4){
            params=new RequestParams(Contacts.ZHUANMAIDIAN+oid+"/edit_anzhuang_attachment");
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        params.addBodyParameter("", "", BOUNDARY);
        for(int i=0;i<photos.size();i++) {
            if(code==4){
                params.addBodyParameter("files[new]["+i+"]",new File(photos.get(i)), BOUNDARY);
            }else {
                params.addBodyParameter("files[" + i + "]", new File(photos.get(i)), BOUNDARY);
            }
            params.addBodyParameter("","", BOUNDARY);
            if(code==1) {
                if (listcid.get(i).id != null) {
                    params.addBodyParameter("files[" + i + "]" + "[cid]", listcid.get(i).id, BOUNDARY);
                }
            }
        }
        x.http().post(params, Call(context, onUserDataInterface));
    }
    /**删除订单照片*/
    public static void deleteWtPhoto(int code,Context context, List<String> listfid,String oid, OnUserDataInterface onUserDataInterface){
        String s="";
        if(code==1){
            s=Contacts.DELETE_WT_PHOTO+oid;
        }else if(code==2){
            s=Contacts.DELETE_DD_PHOTO+oid;
        }else if(code ==3 ){
            s=Contacts.DELETE_ANZHUANG_PHOTO+oid;
        }
        for(int i=0;i<listfid.size();i++){
            s=s+"&fids"+"[]"+"="+listfid.get(i);
        }
        RequestParams params=new RequestParams(s);
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        x.http().request(HttpMethod.DELETE, params, Call(context, onUserDataInterface));
    }
    /**删除专卖店照片*/
    public static void zhuanmaidianPhoto(Context context,String uid,List<String> listfid,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.ZHUANMAIDIAN+uid+"/edit_anzhuang_attachment");
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        for(int i=0;i<listfid.size();i++){
            params.addBodyParameter("files[delete]["+listfid.get(i)+"]",listfid.get(i), BOUNDARY);
        }
        params.addBodyParameter("","", BOUNDARY);
        x.http().post(params, Call(context,onUserDataInterface));
    }

    /**更新订单照片*/
    public static void setWtGX(int code,Context context, String  jsString,String  oid, OnUserDataInterface onUserDataInterface) {
        RequestParams params=null;
        if(code==1){
            params=new RequestParams(Contacts.GX_WT_PHOTO+oid);
        }else if(code==2){
            params=new RequestParams(Contacts.GX_DD_PHOTO+oid);
        }else if(code ==3){
            params=new RequestParams(Contacts.HTTP+"/?q=app/installer_pic/"+oid);
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        params.setBodyContent(jsString);
        x.http().request(HttpMethod.PUT, params, Call(context, onUserDataInterface));
    }
    /**获取组员信息*/
    public static void getXiaoZu(int page,int pagesize,String name,String gonghao,String zuhao,Context context,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIJIAN_XIAOZU);
        getparams(context,params);
        params.addBodyParameter("page",String.valueOf(page));
        params.addBodyParameter("pagesize",String.valueOf(pagesize));
        params.addBodyParameter("searchParams[wu_name]",name);
        params.addBodyParameter("searchParams[work_number]",gonghao);
        params.addBodyParameter("searchParams[gnum]",zuhao);
        x.http().get(params, Call(context, onUserDataInterface));
    }

    /**设置计件组员*/
    public static void setZuYuan(Context context,String jo,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JJ_SC_BENZU);
        getparams(context,params);
        addtoken(params);
        params.addHeader("Content-Type", "application/json");
        params.setBodyContent(jo);
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /**上传计件扫描数据*/
    public static void setJiJianSaoMiao(Context context,String jo,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIJIANSAOMA);
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        params.setBodyContent(jo);
        params.addHeader("Content-Type", "application/json");
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /**分配节号*/
    public static void setjiehao(Context context,String jo,String jiehao,int code,OnUserDataInterface onUserDataInterface){
        RequestParams params;
        if(code==1){
            params=new RequestParams(Contacts.GET_JIEHAO_SHUJU+"/"+jiehao);
        }else if(code==2){
            params=new RequestParams(Contacts.GET_ZHIXIANG_SHUJU+"/"+jiehao);
        }else{
            params=new RequestParams(Contacts.GET_XISU_ZHIXIANG_SHUJU+"/"+jiehao);
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        params.addHeader("Content-Type", "application/json");
        params.setBodyContent(jo);
        x.http().request(HttpMethod.PUT, params, Call(context, onUserDataInterface));
    }
    /**上传节号*/
    public static void addjiehao(Context context,String jo,int code,OnUserDataInterface onUserDataInterface){
        RequestParams params;
        if(code==1){
            params=new RequestParams(Contacts.GET_JIEHAO_SHUJU);
        }else{
            params=new RequestParams(Contacts.GET_ZHIXIANG_SHUJU);
        }
        getparams(context,params);
        addtoken(params);
        setProsess(params);
        params.addHeader("Content-Type", "application/json");
        params.setBodyContent(jo);
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /**获取安装指南*/
    public static void getanzhuang(Context context,int page,int pagesize,String searchParams,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.ANZHUANG_ZHINAN);
        getparams(context, params);
        params.addBodyParameter("page", String.valueOf(page));
        params.addBodyParameter("pagesize", String.valueOf(pagesize));
        params.addBodyParameter("searchParams[installer_guide_title]",searchParams);
        x.http().get(params,Call(context,onUserDataInterface));
    }
    /**获取设计指南*/
    public static void getsheji(Context context,int page,int pagesize,String searchParams,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.SHEJI_ZHINAN);
        getparams(context, params);
        params.addBodyParameter("page", String.valueOf(page));
        params.addBodyParameter("pagesize", String.valueOf(pagesize));
        params.addBodyParameter("searchParams[installer_guide_title]",searchParams);
        x.http().get(params,Call(context,onUserDataInterface));
    }
    /**获取验证码*/
    public static void getYanZheng(Context context,String phone ,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.GET_YANZHENG);
        addssl(params,context);
        params.addBodyParameter("phone",phone, BOUNDARY);
        params.addBodyParameter("","", BOUNDARY);
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /**验证验证码*/
    public static void YanZheng(Context context,String phone ,String yanzheng,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.YANZHENG);
        addssl(params,context);
        params.addBodyParameter("phone",phone, BOUNDARY);
        params.addBodyParameter("code",yanzheng, BOUNDARY);
        x.http().post(params,Call(context,onUserDataInterface));
    }
    /**获取物料质量代码*/
    public static void getZhiLiangDaiMa(Context context,OnUserDataInterface onUserDataInterface){
        RequestParams params =new RequestParams(Contacts.ZHILIAN_DAIMA);
        getparams(context,params);
        x.http().get(params,Call(context,onUserDataInterface));
    }
    /**获取物料类别代码*/
    public static void getWuLiao_LeiBie_DaiMa(Context context,OnUserDataInterface onUserDataInterface){
        RequestParams params =new RequestParams(Contacts.WULIAO_DAIMA);
        getparams(context,params);
        x.http().get(params,Call(context,onUserDataInterface));
    }
    /**获取工号别表*/
    public static void getZhiLiangGongHaoLieBiao(Context context,OnUserDataInterface onUserDataInterface){
        RequestParams params =new RequestParams(Contacts.ZHILIAN_GONGHAO);
        Log.d("TAAAG","params="+params.toString());
        getparams(context,params);
        x.http().get(params,Call(context,onUserDataInterface));
    }

    /**删除板件质量*/
    public static void deleteZhiLiang(Context context,String id,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.XIUGAI_ZHILIANG+"/"+id);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        x.http().request(HttpMethod.DELETE, params, Call(context, onUserDataInterface));
    }


    /**删除计件采集数据*/
    public static void deleteJiJianCaiJi(Context context,String id,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.DELETE_JIJIAN_CAIJI+id);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        x.http().request(HttpMethod.CONNECT.DELETE,params,Call(context,onUserDataInterface));
    }
    /**修改投诉建议*/
    public static void setTouSu(Context context, int code, TouSuBean bean, List<TouSuBean.photo> deletephoto, OnUserDataInterface onUserDataInterface){
        RequestParams params = null;
        if(code==1){
            params=new RequestParams(Contacts.TOUSU);
        }else if(code==2){
            params=new RequestParams(Contacts.TOUSU+"/"+bean.id+"/edit");
        }
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        params.addBodyParameter("han_qu",bean.chuangqu, BOUNDARY);
        params.addBodyParameter("bu_men",bean.bumen, BOUNDARY);
        params.addBodyParameter("complaint",bean.tousu, BOUNDARY);
        params.addBodyParameter("suggestion",bean.jianyi, BOUNDARY);
        params.addBodyParameter("reply",bean.reply, BOUNDARY);
        if(QuanXian.Companion.isXiuGaiTouSuTudy()){
            params.addBodyParameter("duty_bumen",bean.duty_bumen, BOUNDARY);
            params.addBodyParameter("duty_name",bean.duty_name, BOUNDARY);
        }
        for(int i=0;i<bean.photoList.size();i++){
            TouSuBean.photo photo=bean.photoList.get(i);
            if(photo.fid.equals("")){
                params.addBodyParameter("files[new]["+i+"]",new File(photo.uri), BOUNDARY);
            }
        }
        for(int i=0;i<deletephoto.size();i++){
            if(!deletephoto.get(i).fid.equals("")) {
                params.addBodyParameter("files[delete][" + deletephoto.get(i).fid + "]", deletephoto.get(i).fid, BOUNDARY);
            }
        }
        Log.d("TAAAG","p="+params.toString());
        Log.d("TAAAG","p="+bean.toString());
        x.http().post(params, Call(context, onUserDataInterface));
    }

    /**获取意见*/
    public static void tousubiao(Context context,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.TOUSU_BIAO);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /**删除指定id的供应材料质量*/
    public static void deleteCodeCaiLiao(Context context,String id, OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.CAILIAO_ZHILIANG+"/"+id);
        getparams(context, params);
        addtoken(params);
        x.http().request(HttpMethod.DELETE, params, Call(context, onUserDataInterface));
    }

    /**获取家纺列表*/
    public static void getJiaFangLieBiao(Context context,int page,int pagesize,String leixing,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO);
        getparams(context, params);
        setProsess(params);
        params.addBodyParameter("page", String.valueOf(page));
        params.addBodyParameter("pagesize", String.valueOf(pagesize));
        params.addBodyParameter("searchParams[iioo_type]", leixing);
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /**获取货品编码信息*/
    public static void getJiaFangBianMa(Context context,String bianma,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+bianma+"/jiafang_info");
        getparams(context, params);
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /**获取生产单信息*/
    public static void getJiaFangDanJu(Context context,String danju,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+danju+"/jiafang_order");
        getparams(context, params);
        setProsess(params);
        x.http().get(params, Call(context, onUserDataInterface));
    }
    /**上传家纺*/
    public static void addJiaFang(Context context, List<AddJiaFangBean> mlist,String iw_id,String iioo_type,String remark,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        params.addBodyParameter("iioo_type",iioo_type,BOUNDARY);
        params.addBodyParameter("iw_id",iw_id,BOUNDARY);
        params.addBodyParameter("remark",remark,BOUNDARY);
        for(int i=0;i<mlist.size();i++){
            params.addBodyParameter("goods[new]["+i+"][gi_id]",mlist.get(i).id,BOUNDARY);
            params.addBodyParameter("goods[new]["+i+"][amount]",mlist.get(i).amount,BOUNDARY);
            if(!mlist.get(i).oid.equals("")) {
                params.addBodyParameter("goods[" + i + "][oid]", mlist.get(i).oid, BOUNDARY);
            }
        }
        x.http().post(params, Call(context, onUserDataInterface));
    }
    /**修改家纺*/
    public static void xiuGaiFang(Context context,JSONObject jo,String id, OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+id+"/edit");
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        params.setBodyContent(jo.toString());
        Log.d("TAAG",jo.toString());
        x.http().post(params, Call(context, onUserDataInterface));
    }
    /**审核家纺*/
    public static void shenHeJiaFang(Context context,JSONObject jo,String id, OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+id);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        params.setBodyContent(jo.toString());
        x.http().request(HttpMethod.PUT,params, Call(context,onUserDataInterface));
    }
    /**删除家纺*/
    public static void deleteJiaFang(Context context,String id, OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+id);
        getparams(context, params);
        addtoken(params);
        setProsess(params);
        x.http().request(HttpMethod.DELETE,params, Call(context,onUserDataInterface));
    }
    /**获取家纺单数据*/
    public static void getJiaFangDanData(Context context,String id,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.JIAFANG_LIEBIAO+"/"+id);
        getparams(context, params);
        setProsess(params);
        Log.d("TAAG",params.toString());
        x.http().get(params,Call(context,onUserDataInterface));
    }
    /**上传错误信息*/
    public static void updataError(Context context,String uid,String url,OnUserDataInterface onUserDataInterface){
        RequestParams params=new RequestParams(Contacts.UPDATA_ERROR+uid);
        getparams(context, params);
        addtoken(params);
        params.addBodyParameter("","", BOUNDARY);
        params.addBodyParameter("files[0]", new File(url), BOUNDARY);
        params.setConnectTimeout(5000);
        Log.d("UnCeHandler","上传1"+url+ "     "+params.toString());
        x.http().post(params, Call(context, onUserDataInterface));
    }
    /**
     * 为params添加token
     */
    public static void addtoken(RequestParams params){
        Log.d("TAAG","token="+Sputil.sp("erp").getString("token", ""));
        params.addHeader("X-CSRF-TOKEN", Sputil.sp("erp").getString("token", ""));
    }

    public static void setProsess(RequestParams params){
        params.addParameter("x-oss-process-2","image/resize,m_lfit,w_200,h_200");
    }
    /**
     * 为params添加cookie和ssl证书
     * @param context
     * @param params
     */
    public static void getparams(Context context, RequestParams params) {
        addssl(params,context);
        params.setUseCookie(false);
        addcookie(params);
        params.addHeader("Accept", "application/json");
        params.setConnectTimeout(20000);
    }

    public static void getparams2(Context context, RequestParams params) {
//        addssl(params,context);
        addcookie2(params);
//        params.setConnectTimeout(20000);
    }

    /**
     * 获取Https的证书
     *
     * @param context Activity（fragment）的上下文
     * @return SSL的上下文对象
     */
    public static SSLContext getSSLContext(Context context) {
        if(sslContext!=null){
            return sslContext;
        }
        try {
//            String keyPassphrase = "huabiaoapp9364";
            String keyPassphrase = BuildConfig.Pfx+context.getResources().getString(R.string.pfx)+Contacts.pfx();
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(context.getResources().getAssets().open("appke_hu_duan_.pfx"), keyPassphrase.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, keyPassphrase.toCharArray());
            KeyManager[] kms = kmf.getKeyManagers();
//            KeyStore trustStore = KeyStore.getInstance("BKS");
////            trustStore.load(context.getResources().getAssets().open("erp.knoya.com.bks"), "huabiaoapp9364bks".toCharArray());
//            trustStore.load(context.getResources().getAssets().open("erp.knoya.com.bks"), (BuildConfig.Pfx+context.getResources().getString(R.string.pfx)+Contacts.pfx()+"bks").toCharArray());
//            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            tmf.init(trustStore);
//            TrustManager[] tms = tmf.getTrustManagers();
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(kms,tms,new SecureRandom());
            sslContext.init(kms, new TrustManager[]{new X509TrustManager() {


                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());

            return sslContext;
        } catch (Exception e) {
            Log.e("tag", e.getMessage(), e);
        }
        return null;
    }
    public static SSLContext getSSLContext1(Context context) {
        if(sslContext!=null){
            return sslContext;
        }
        try {
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }
            }}, new SecureRandom());

            return sslContext;
        } catch (Exception e) {
            Log.e("tag", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 为网络访问添加cookie参数
     *
     * @param params          RequestParams对象
     */
    public static void addcookie(RequestParams params) {
        Log.d("TAAG","COOKIE"+Sputil.sp("erp").getString("cookie", ""));
        params.addHeader("COOKIE", Sputil.sp("erp").getString("cookie", ""));
    }

    public static void addcookie2(RequestParams params) {

        String cookie = Sputil.sp("erp").getString("cookie", "")+"; "+Sputil.sp("erp").getString("laravelcookie", "");

        cookie = "SSESS6a3d1348dd9429a4cebafb620fc8970a=1YjOlNLI7Tyj1tpu4pOK6QntJfCz1PSfC1c6tmvma54; ";
        Log.d("COOKIE","COOKIE="+cookie);
        params.addHeader("COOKIE", cookie);
    }
    private static SSLContext sslContext;
    /**
     * 为网络访问添加ssl证书
     *
     * @param params           RequestParams对象
     * @param context          上下文
     */
    public static void addssl(RequestParams params, Context context) {
        if (null == sslContext) {
            sslContext=getSSLContext(context);
        }
        //绑定SSL证书
        params.setSslSocketFactory(new Tls12SocketFactory(sslContext.getSocketFactory()));
    }

    /**
     * 下载文件的返回
     *
     * @param onUserDataInterface 回调监听
     * @param pb                  进度条
     * @param tv                  百分比
     * @return
     */
    public static Callback.ProgressCallback<File> Callfile(final Context context, final OnUserDataInterface onUserDataInterface, final ProgressBar pb, final TextView tv) {
        Callback.ProgressCallback<File> callfiles = new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long l, long l1, boolean b) {
                int schedule = (int) ((l1 * 100) / l);
                pb.setProgress(schedule);
                tv.setText(schedule + "%");
            }

            @Override
            public void onSuccess(File file) {
                Myutil.MyTost("下载成功" + file.toString());
                onUserDataInterface.onUserData(file.toString());
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                Myutil.onerror(throwable.toString(), (Activity) context);
                Myutil.MyTost("下载失败");
                Myutil.Mylog("TAAAG",throwable.toString());
                onUserDataInterface.onNot(throwable.toString());
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        };
        return callfiles;
    }

    /**
     * 加载图片的builder
     * @param mcontext
     * @return
     */
    public static  ImageOptions.ParamsBuilder getop(final Context mcontext){
        ImageOptions.ParamsBuilder builder=new ImageOptions.ParamsBuilder() {
            @Override
            public RequestParams buildParams(RequestParams requestParams, ImageOptions imageOptions) {
                requestParams.addHeader("COOKIE", Sputil.sp("erp").getString("cookie", ""));
                Httputil.addssl(requestParams, mcontext);
                return requestParams;
            }
        };
        return builder;
    }

    /**
     * 获取数据的返回
     * @param onUserDataInterface
     * @return
     */
    public static Callback.CommonCallback<String> Call(final Context context, final OnUserDataInterface onUserDataInterface) {

        return new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result)
            {
                Log.d("TAAG","result="+result.toString());
                Log.d("onSuccess",result);
                onUserDataInterface.onUserData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("TAAG","ex="+ex.toString());
                if(ex.toString().trim().contains("a.a")){
                    Log.d("TAAG","ex=xxxxxxxxxxxxxxxxxxxxxx"+ex.toString());
                    onUserDataInterface.onNot(ex.toString());
                    return;
                }
                boolean isonerror = false;
                if (!isOnCallback) {
                    isonerror=Myutil.onerror(ex.toString(),(Activity) context);
                    onUserDataInterface.onNot(ex.toString());
                    if(isonerror){
                        return;
                    }
                }
                String[] ss = ex.toString().split("result:");
                if(ss.length>1) {
                    String edata = "";
                    try {
                        JSONArray js = new JSONArray(ss[1]);
                        if (js.length() != 0) {
                            edata = js.getString(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if(!edata.trim().equals("")){
                        Myutil.httperrordiaog(context,Myutil.decodeUnicode(edata));
//                        Myutil.MyTost(Myutil.decodeUnicode(edata));
                    }else{
                        Myutil.MyTost(Myutil.decodeUnicode(ss[1]));
                    }
                }else{
                    Myutil.MyTost(Myutil.decodeUnicode(ex.toString()));
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        };
    }
}
